package solution101;

import java.util.LinkedList;
import java.util.Queue;

/**
 *  101. Symmetric Tree
 *  判断二叉树是否是平衡树，比如有两个节点n1, n2，除了比较结点的值是否相等，
 *  我们需要比较n1的左子节点的值和n2的右子节点的值是否相等，
 *  同时还要比较n1的右子节点的值和n2的左子结点的值是否相等，
 *  以此类推比较完所有的左右两个节点。
 *  Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
 *  For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
 *        1
 *      / \
 *     2   2
 *   / \ / \
 * 3  4 4  3
 * But the following [1,2,2,null,3,null,3] is not:
 *      1
 *    / \
 *  2   2
 *   \   \
 *   3    3
 */
public class Solution {

    // 递归方法Recursive
    public boolean isSymmetric(TreeNode root) {
        return (root == null) || isSymmetric(root.left, root.right);// 判断是否对称
    }

    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null || right == null)
            return left == right;
        return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }

    // 迭代方法Iteration
    public boolean isSymmetricIteratively(TreeNode root) {
        if (root == null) return true;
        Queue<TreeNode> queue1 = new LinkedList<>();
        Queue<TreeNode> queue2 = new LinkedList<>();
        queue1.add(root.left);
        queue2.add(root.right);
        while (queue1.size()!=0 && queue2.size()!=0) {
            TreeNode q1 = queue1.poll();
            TreeNode q2 = queue2.poll();
            if ((q1 == null && q2 != null) || (q1 != null && q2 == null)) return false;
            if (q1!=null) {
                if (q1.val != q2.val) return false;
                queue1.add(q1.left);
                queue1.add(q1.right);
                queue2.add(q2.right);// 对称加入
                queue2.add(q2.left);
            }
        }
        return true;
    }
}
